<?php
namespace app\mobile\controller;

use app\common\model\CardGeneral;
use app\common\model\CardGoods;
use app\common\model\CardMember;
use app\common\model\CardMemberAli;
use app\common\model\CardOrder;

use app\common\model\CardUserGet;

use app\common\model\Agent;
use app\common\model\CardUserUpdate;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use app\common\model\Merchant;
use app\common\model\System;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;
class Cardshopali extends Mobileali
{

//    public function orderconf($id){
//        $map['id'] = $id;
//        $CardGoods = new CardGoods();
//        $list =$CardGoods->where($map)->order('id asc')->select();
//        $this->assign('list', $list);
//        return $this->fetch();
//    }

    //积分商城首页：商品列表
    /*
     * 参数
     * 商品列表
     */
    public function goods()
    {
        $this->_init();
        $arr = request()->param();
//        $map['template_id'] = '20180310000000000852187000300944';
        $map['mid'] = $arr['mid'];
        $map['user_id'] = Session::get('card_user_id');
        $map['card_type'] = 'OUT_MEMBER_CARD';
        $map['have'] = 1;
        $CardUserGetAli = new CardMemberAli();
        $info = $CardUserGetAli->where($map)->find();
        $CardGoods = new CardGoods();
        $CardOrder = new CardOrder();
        $map['template_id'] = $info['template_id'];
        $map['statu'] = ['neq',2];
        $list = $CardGoods->where($map)->order('id asc')->select();
        $map['user_id'] = Session::get('card_user_id');
        $order = $CardOrder->where($map)->order('id desc')->select();
        //JSSDK
        $this->assign('list',$list);
        $this->assign('order',$order);
        $CardMemberAli = new CardMemberAli();
        $is_bonus_shop = $CardMemberAli->where('template_id', $info['template_id'])->value('is_bonus_shop');
        if ($is_bonus_shop == 1) {
            return $this->fetch();
        } else {
            return $this->fetch('off');
        }
    }

    //积分商城商品
    /*
     * 参数
     * $id,$card_id
     */
    public function goodsdetail($id, $card_id)
    {
        $this->_init();
        $CardGoods = new CardGoods();
        $info = $CardGoods->where(['id' => $id])->find();
        //检查商品状态
        $arr['id'] = $id;
        $check_res = $this->check_goods($arr);
        $info['ver_statu'] = $check_res;
        $card['card_id'] = $card_id;
        //JSSDK
        $share['wxjssdk'] = $this->getsharejssdk($card_id);
        $share['wxjssdk'] = json_encode($share['wxjssdk']);
        $this->assign('share',$share);
        $this->assign('card', $card);
        $this->assign('info', $info);
        return $this->fetch();
    }

    //订单详情
    /*
     * 订单id 会员卡$card_id
     *
     * $id $card_id
     */
    public function orderinfo($id,$card_id){
        $this->_init();
        $map['card_id'] = $card_id;
        $map['openid'] = Session::get('card_openid');
        $map['have'] = 1;
        $map['card_type'] = 'MEMBER_CARD';
        $CardUserGet = new CardUserGet();
        $info = $CardUserGet->where($map)->find();
        if ($info) {
            $mab['openid'] = Session::get('card_openid');
            $mab['card_id'] = $card_id;
            $mab['id'] = $id;
            $CardGoods = new CardGoods();
            $CardOrder = new CardOrder();
            $order = $CardOrder->where($mab)->find();
            $goods = $CardGoods->where('id',$order['gid'])->find();
            $this->assign('goods',$goods);
            $this->assign('order', $order);
            return $this->fetch();
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
        }
    }

    /*
     * 提交订单
     * 参数
     * $id $card_id
     */
    public function orderadd($id,$card_id){
        if (Request()->isPost()){
            $arr = request()->post();
            $openid = Session::get('card_openid');
            $CardGoods = new CardGoods();
            $CardUserGet = new CardUserGet();
            $user = $CardUserGet->where(['openid'=>$openid,'card_id'=>$card_id])->find();
            if ($user['bonus'] > $arr['goods_price'] || $user['bonus'] == $arr['goods_price']) {
                $goods = $CardGoods->where('id',$arr['gid'])->find();
                $map['card_id'] = $arr['card_id'];
                $map['openid'] = Session::get('card_openid');
                $data['uid'] = $user['id'];
                $data['card_id'] = $goods['card_id'];
                $data['goods_card_id'] = $goods['goods_card_id'];
                $data['openid'] = Session::get('card_openid');
                $data['code'] = $arr['code'];
                $data['gid'] = $arr['gid'];
                $data['goods_name'] = $goods['goods_name'];
                $data['goods_type'] = $goods['goods_type'];
                $data['goods_img'] = $goods['goods_img'];
                $data['address'] = $arr['address'];
                $data['price'] = $arr['goods_price'];
                $data['phone'] = $arr['phone'];
                $data['number'] = $arr['number'];
                $data['goods_info'] = json_encode($goods,JSON_UNESCAPED_UNICODE);
                $data['create_time'] = time();
                $CardOrder = new CardOrder();
                $add = $CardOrder->allowField(true)->save($data);
                if ($add == false) {
                    $this->error('提交失败', '', 1);
                } else {
                    $data['name'] = $arr['name'];
                    $res = $this->updatebonus($data);
                    if ($res == '0'){
                        //修改库存
                        $CardGoods->where('id',$arr['gid'])->setDec('stock');
                        $CardGoods->where('id',$arr['gid'])->setInc('getsume');
                        //同步积分状态
                        $resu['tplmsg_info'] = json_encode($res,JSON_UNESCAPED_UNICODE);
                        $order_id = $CardOrder->id;
                        $CardOrder->save($resu,['id'=>$order_id]);
                        $this->redirect( url('cardshop/addcard',['order_id'=>$order_id]));
                    }else{
                        $this->error('提交失败', url('carduser/index',['card_id'=>$card_id]), 1);
                    }
                }
            }else{
                $this->success('积分不足', url('carduser/index',['card_id'=>$card_id]),1);
            }
        }else{
            $this->_init();
            $openid = Session::get('card_openid');
            $CardGoods = new CardGoods();
            $CardUserGet = new CardUserGet();
            $goods = $CardGoods->where(array('id'=>$id))->find();
            $user = $CardUserGet->where(['openid'=>$openid,'card_id'=>$card_id])->find();
            //JSSDK
            $share['wxjssdk'] = $this->getsharejssdk($card_id);
            $share['wxjssdk'] = json_encode($share['wxjssdk']);
            $this->assign('share',$share);
            $this->assign('user', $user);
            $this->assign('goods', $goods);
            return $this->fetch();
        }
    }


    //发放卡
    /*
     * 参数
     * $order_id
     */
    public function addcard($order_id)
    {
        $CardOrder = new CardOrder();
        $CardUserGet = new CardUserGet();
        $order = $CardOrder->where('id',$order_id)->find();
        $openid = $order['openid'];
        if ($order['statu'] < '2') {
            $user = $CardUserGet->where(['openid' => $openid, 'card_id' => $order['card_id']])->find();
//            if ($user['bonus'] > $order['price'] || $user['bonus'] == $order['price']) {
            $arr['card_id'] = $order['goods_card_id'];
            $arr['openid'] = $openid;
            //更新订单状态
            $data['statu'] = '2';
            $CardOrder->save($data, ['id' => $order_id]);
            //发放
            $arrs['card_id'] = $arr['card_id'];
            $arrs['openid'] = $arr['openid'];
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $options = $this->options($arr['card_id']);
            $weObj = new Wxobjopen($options);
            $card = $this->put($arrs);
            $jssdk = $weObj->get_card_JsSign($url);
            $this->assign('card', $card);
            $this->assign('jssdk', $jssdk);
            return $this->fetch();
//            } else {
//                $this->success('积分不足', url('carduser/index', ['card_id' => $order['card_id']]), 1);
//            }
        }else{
            $this->success('订单已完成，请勿重复打开！', url('carduser/index', ['card_id' => $order['card_id']]), 1);
        }
    }

    //检查商品
    /*
     * 参数  商品id
     * $arr['id']
     *
     */
    private function check_goods($arr){
        $CardGoods = new CardGoods();
        $map['id'] = $arr['id'];
        $goods = $CardGoods->where($map)->find();
        $time = time();
        //判断商品是否过期
        if ($goods['end_time'] > $time){
            $data['ver_statu'] = 1;         //正常
            //判断是否有库存
            if ($goods['stock'] > $goods['getsume']){
                $data['ver_statu'] = 1;         //正常
                //判断商品类型
                if ($goods['goods_type'] == 'card_dis'){
                    $data['ver_statu'] = 1;         //正常
//                    //判断卡券过期
                    if (filteroffcard($goods['goods_card_id']) == true){
                        $data['ver_statu'] = 1;         //正常
                    }else{
                        $data['ver_statu'] = 16;        //卡券已过期 / 无库存
                    }
                }else{
                    $data['ver_statu'] = 17;         //红包类型未开放
                }
            }else{
                $data['ver_statu'] = 18;         //商品没有库存
            }
        }else{
            $data['ver_statu'] = 19;        //商品超过时间
        }
    }

    //投放卡
    /*
     *  $card_id $openid
     */
    private function put($arr)
    {
        $options = $this->options($arr['card_id']);
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $weObj = new Wxobjopen($options);
        $noncestr = $weObj->generateNonceStr();
        $res['config'] = $weObj->getJsSign($url, '', $noncestr);
        $res['config']['debug'] = true;
        $res['config']['jsApiList'] = array('addCard', 'openCard', 'chooseCard');
        $res['card_id'] = $arr['card_id'];
        $res['addcard'] = $weObj->wxAddCard($arr['openid'], $arr['card_id'], $noncestr);
        return $res;
    }

    //更新会员数据
    /*
     * $arr['card_id'] / $arr['code'] / $arr['price'] / $arr['name'] / $data['add_bonus']
     *
     */
    public function updatebonus($arr){
        $data = array(
            'card_id'=>$arr['card_id'],
            'code'=> $arr['code'],
            'add_bonus'=>-$arr['price'],
            'record_bonus'=>'积分兑换:'.$arr['name'],
            "notify_optional"=>array(
                "is_notify_bonus"=>true,
                "is_notify_balance"=> true,
                "is_notify_custom_field1"=>true
            )
        );
        $options = $this->options($arr['card_id']);
        $weObj = new Wxobjopen($options);
        $res = $weObj->updateUserInfo($data);
        if ($res['errcode'] == 0){
            $bonus['del_bonus']=abs($data['add_bonus']);
            $bonus['record_bonus'] = '积分兑换:'.$arr['name'];
            $bonus['openid']=$arr['openid'];
            $bonus['card_id']=$arr['card_id'];
            $bonus['code']=$arr['code'];
            $bonus['create_time'] = time();
            $bonus['outerstr'] = 'BONUSSHOP';
            $bonus['tplmesg_info'] = json_encode($res);
            $CardUserUpdate = new CardUserUpdate();
            $CardUserGet = new CardUserGet();
            $CardUserUpdate->allowField(true)->save($bonus);
            $map['openid'] = $bonus['openid'];
            $map['card_id'] = $bonus['card_id'];
            $CardUserGet->where($map)->setField('bonus', $res['result_bonus']);
            return '0';
        }else{
            return "1";
        }
    }

    //分享jssdk
    /*
     * $card_id
     */
    private function getsharejssdk($arr){
//        return $arr;
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->options($arr);
        //分享
        $weObj = new Wxobjopen($options);
        $jssdk = $weObj->getJsSign($url);
        $wxJsSdk = [
            'debug' => false,
            'appId' => $jssdk['appId'],
            'timestamp' =>$jssdk['timestamp'],
            'nonceStr' => $jssdk['nonceStr'],
            'signature' => $jssdk['signature'],
            'jsApiList' => [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareQZone',
                'closeWindow',
                'hideAllNonBaseMenuItem',
            ]
        ];
        return $wxJsSdk;
    }



}
